package com.css.zfzx.sjcj.modules.hddcGeophySvyPoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.superRepository.SuperRepository;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.repository.entity.HddcB4SampledatatableEntity;
import com.css.zfzx.sjcj.modules.hddcB5_GeophySvyDataTable.repository.entity.HddcB5GeophysvydatatableEntity;
import com.css.zfzx.sjcj.modules.hddcB5_GeophySvyDataTable.service.HddcB5GeophysvydatatableService;
import com.css.zfzx.sjcj.modules.hddcGeophySvyLine.repository.entity.HddcGeophysvylineEntity;
import com.css.zfzx.sjcj.modules.hddcGeophySvyLine.service.HddcGeophysvylineService;
import com.css.zfzx.sjcj.modules.hddcGeophySvyPoint.repository.HddcGeophysvypointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeophySvyPoint.repository.HddcGeophysvypointRepository;
import com.css.zfzx.sjcj.modules.hddcGeophySvyPoint.repository.entity.HddcGeophysvypointEntity;
import com.css.zfzx.sjcj.modules.hddcGeophySvyPoint.service.HddcGeophysvypointService;
import com.css.zfzx.sjcj.modules.hddcGeophySvyPoint.viewobjects.HddcGeophysvypointQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeophySvyPoint.viewobjects.HddcGeophysvypointVO;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.repository.entity.HddcSamplepointEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author zhangcong
 * @date 2020-11-28
 */
@Service
public class HddcGeophysvypointServiceImpl implements HddcGeophysvypointService {

	@Autowired
    private HddcGeophysvypointRepository hddcGeophysvypointRepository;
    @Autowired
    private HddcGeophysvypointNativeRepository hddcGeophysvypointNativeRepository;
    @Autowired
    private HddcB5GeophysvydatatableService hddcB5GeophysvydatatableService;

    @Override
    public JSONObject queryHddcGeophysvypoints(HddcGeophysvypointQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeophysvypointEntity> hddcGeophysvypointPage = this.hddcGeophysvypointNativeRepository.queryHddcGeophysvypoints(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGeophysvypointPage);
        return jsonObject;
    }


    @Override
    public HddcGeophysvypointEntity getHddcGeophysvypoint(String id) {
        HddcGeophysvypointEntity hddcGeophysvypoint = this.hddcGeophysvypointRepository.findById(id).orElse(null);
         return hddcGeophysvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeophysvypointEntity saveHddcGeophysvypoint(HddcGeophysvypointEntity hddcGeophysvypoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeophysvypoint.setUuid(uuid);
        hddcGeophysvypoint.setQualityinspectionStatus("0");
        hddcGeophysvypoint.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGeophysvypoint.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGeophysvypoint.setIsValid("1");
        this.hddcGeophysvypointRepository.save(hddcGeophysvypoint);
        return hddcGeophysvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeophysvypointEntity updateHddcGeophysvypoint(HddcGeophysvypointEntity hddcGeophysvypoint) {
        UpdateUtil.copyNullProperties(hddcGeophysvypointRepository.findByUuidAndIsValid(hddcGeophysvypoint.getUuid(),
                "1"), hddcGeophysvypoint);
        hddcGeophysvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeophysvypoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeophysvypointRepository.save(hddcGeophysvypoint);
        return hddcGeophysvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeophysvypoints(List<String> ids) {
        List<HddcGeophysvypointEntity> hddcGeophysvypointList = this.hddcGeophysvypointRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeophysvypointList) && hddcGeophysvypointList.size() > 0) {
            for(HddcGeophysvypointEntity hddcGeophysvypoint : hddcGeophysvypointList) {
                hddcGeophysvypoint.setIsValid("0");
                hddcGeophysvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeophysvypoint.setUpdateTime(new Date());
                this.hddcGeophysvypointRepository.save(hddcGeophysvypoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGeophysvypointQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeophysvypointEntity> yhDisasterEntities = hddcGeophysvypointNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeophysvypointVO> list=new ArrayList<>();
        for (HddcGeophysvypointEntity entity:yhDisasterEntities) {
            HddcGeophysvypointVO yhDisasterVO=new HddcGeophysvypointVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"地球物理测点-点","地球物理测点-点",HddcGeophysvypointVO.class,"地球物理测点-点.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeophysvypointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeophysvypointVO.class, params);
            List<HddcGeophysvypointVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeophysvypointVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeophysvypointVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public HddcGeophysvypointEntity findById(String id) {
        return hddcGeophysvypointRepository.findbyId(id);
    }
    @Autowired
    SuperRepository superRepository;
    @Override
    @Transactional
    public int dataQualityCheck() {
        List<HddcGeophysvypointEntity> updateList =new ArrayList<>();
        List<HddcGeophysvypointEntity> listAll = hddcGeophysvypointRepository.findByAll();
        for (HddcGeophysvypointEntity b2All: listAll) {
            String str="";
            if (StringUtils.isEmpty(b2All.getId())) {
                str += "【地球物理测点】测点编号为空。";
            } else {
                HddcB5GeophysvydatatableEntity hddcB5GeophysvydatatableEntity = hddcB5GeophysvydatatableService.findBySvypointid(b2All.getId());
                if (hddcB5GeophysvydatatableEntity == null) {
                    str += "【地球物理测点】表单中的测点编号与【地球物理探测数据表】中的测点编号不一致。";
                } else {
                    if (StringUtils.isEmpty(b2All.getSvylineid())) {
                        str += "【地球物理测点】测线编号为空。";
                    } else {
                        if (!b2All.getSvylineid().equals(hddcB5GeophysvydatatableEntity.getSvylineid())) {
                            str += "【地球物理测点】表单中的测线编号与【地球物理探测数据表】中的测线编号不一致。";
                        }
                    }
                    if (StringUtils.isEmpty(b2All.getSvymethod()) || "null".equals(b2All.getSvymethod())) {
                        str += "【地球物理测点】探测方法为空。";
                    } else {
                        if (!b2All.getSvymethod().equals(hddcB5GeophysvydatatableEntity.getSvymethod())) {
                            str += "【地球物理测点】表单中的探测方法与【地球物理探测数据表】中的探测方法不一致。";
                        }
                    }
                }
            }
            if (str.isEmpty()) {
                str += "【地球物理测点】与【地球物理探测数据表】质检成功。";
                b2All.setQualityinspectionStatus("1");
            }else {
                b2All.setQualityinspectionStatus("2");
            }
            b2All.setQualityinspectionComments(null);
            String[] split = str.split("。");
            for (int i = 0; i < split.length; i++) {
                if (i == 0) {
                    b2All.setExtends1(split[i]);
                    b2All.setExtends2(null);
                    b2All.setExtends3(null);
                } else if (i == 1) {
                    b2All.setExtends2(split[i]);
                    b2All.setExtends3(null);
                } else if (i == 2) {
                    b2All.setExtends3(split[i]);
                }
            }
            updateList.add(b2All);
        }
        superRepository.batchUpdate(updateList);
        return 1;
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcGeophysvypointVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeophysvypointEntity yhDisasterEntity = new HddcGeophysvypointEntity();
            HddcGeophysvypointVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeophysvypoint(yhDisasterEntity);
        }
    }

}
